﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLDC.Topo.BLL.Estate;
using System.Data;
using ZLDC.Common.Estate;
using ZLDC.Common.BaseUser;
using System.Text.RegularExpressions;
namespace ZLDC.Estate.TM
{
    public partial class RoomNo : _PageBase
    {
        RoomNoBLL rbll = new RoomNoBLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                string type = Request.QueryString["type"].ToString();
                if (type == "Update")//修改房号
                {
                    string value = Request.QueryString["value"].ToString();//栋阁ID
                    int bid = Convert.ToInt32(Request.QueryString["bid"]);
                    txtBid.Text = bid.ToString();
                    DataSet dd = rbll.SelectNameByBid(bid);
                    lblEname.Text = dd.Tables[0].Rows[0]["ename"].ToString();

                    ZLDC.Topo.BLL.Estate.SystemParamBLL.LoadUsage(ddlUsage, false, "用途");                    
                   
                    //窗体加载时，加载栋阁信息
                    int eid = Convert.ToInt32(dd.Tables[0].Rows[0]["eid"]);
                    buildName1.DataSource = GetBnameByEid(eid);
                    buildName1.DataValueField = "id";
                    buildName1.DataTextField = "finalName";
                    buildName1.DataBind();
                    DataSet ds = rbll.SelectRoomsById(value);
                    txtFloor.Text = ds.Tables[0].Rows[0]["floor"].ToString();
                    txtRoomNo.Text = ds.Tables[0].Rows[0]["name"].ToString();
                    txtOtherName.Text = ds.Tables[0].Rows[0]["othername"].ToString();
                    remark.Text = ds.Tables[0].Rows[0]["remark"].ToString();
                    string status = ds.Tables[0].Rows[0]["bstatus"].ToString();
                    buildName1.Items.Insert(0, "请选择");


                }
                else if (type == "Add" || type == "SqAdd")//添加,申请房号
                {
                    ZLDC.Topo.BLL.Estate.SystemParamBLL.LoadUsage(ddlUsage, false, "用途");

                    int bid = Convert.ToInt32(Request.QueryString["value"]);
                    txtBid.Text = bid.ToString();
                    DataSet ds = rbll.SelectNameByBid(bid);
                    lblEname.Text = ds.Tables[0].Rows[0]["ename"].ToString();
                    int eid = Convert.ToInt32(ds.Tables[0].Rows[0]["eid"]);
                    if (type == "SqAdd")
                    {
                        //ddlBuild.DataSource = rbll.SelectNameByBid(bid);
                        //ddlBuild.DataValueField = "id";
                        //ddlBuild.DataTextField = "finalName";
                        //ddlBuild.DataBind();

                        buildName1.DataSource = rbll.SelectNameByBid(bid);
                        buildName1.DataValueField = "id";
                        buildName1.DataTextField = "finalName";
                        buildName1.DataBind();
                        buildName1.Items.Insert(0, "请选择");


                    }
                    else if (type == "Add")
                    {
                        buildName1.DataSource = rbll.SelectNameByBid(bid);
                        buildName1.DataValueField = "id";
                        buildName1.DataTextField = "finalName";
                        buildName1.DataBind();
                        buildName1.Items.Insert(0, "请选择");
                    }
                }
            }

        }


        /// <summary>
        /// 通过楼盘ID取栋阁名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static DataSet GetBnameByEid(int id)
        {
            string sql = "select id,finalName from t_build where eid='" + id + "'";

            DataSet ds = null;
            using (_Database db = new _Database("estate"))
            {
                ds = db.Query(sql);
            }

            return ds;
        }
        //保存房间号信息
        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                int isvalid = 1;      // 0有效 1待审核 2无效    

                // 权限判断
                if (ZLDC.Common.BaseUser.UserInfo.GetPopedom("直接添加房号"))
                    isvalid = 0;

                string type = Request.QueryString["type"].ToString();//操作类型
                string othername = txtOtherName.Text;//别名
                int floor = _Convert.ToInt(txtFloor.Text, 0);//层数
                string mark = remark.Text.Trim();//备注
                // int bid = Convert.ToInt32(buildName1.SelectedIndex);//栋阁ID
                int bid = _Convert.ToInt(build_id.Text, 0);
                string bname = "";

                DataTable dt=ZLDC.Topo.BLL.Estate.BuildBLL.BuildDetail1(bid);
                if(dt.Rows.Count>0){
                     bname = dt.Rows[0]["finalName"].ToString();//楼盘栋阁名称
                }

                //添加前缀后缀
                string strPer = iNameFirst.Value;
                string strLast = iNameEnd.Value;

                string usage = ddlUsage.SelectedValue.ToString();//类型
                //string statusid = ddlstatus.Value.ToString(); //状态

                string statusid = "0";
                string value = Request.QueryString["value"].ToString();//房号ID
                string othernamepy = _Utility.GetChineseSpell(othername);
                if (hType.Value == "1")
                {
                    string name = txtRoomNo.Text;
                    string namepy = _Utility.GetChineseSpell(name);
                    if (txtFloor.Text.Trim() == "")
                    {
                        ClientScript.RegisterStartupScript(typeof(string), "", "<script>alert('请输入层数！')</script>");
                        txtFloor.Focus();
                        return;

                    }
                    if (txtRoomNo.Text.Trim() == "")
                    {
                        ClientScript.RegisterStartupScript(typeof(string), "", "<script>alert('请输入房间号！')</script>");
                        txtRoomNo.Focus();
                        return;

                    }

                    int count = ZLDC.Topo.BLL.Estate.RoomNoBLL.SelectRooms(bid.ToString(), floor.ToString(), name);//验证房号是否存在
                    if (count > 0)
                    {
                        ClientScript.RegisterStartupScript(typeof(string), "", "<script>alert('该房号已存在！')</script>");
                    }
                    if (rbll.AddRoomNos(name, othername, floor, bid, bname, mark, type, value, usage, this.info.m_sUserName, this.info.m_sDeptName, this.info.m_sDeptID, statusid, namepy, othernamepy, isvalid) > 0)
                    {
                        if (typeid.Text == "")
                        {
                            ClientScript.RegisterStartupScript(typeof(string), "", "<script>window.close();</script>");
                        }
                        else if (typeid.Text == "1")
                        {
                            ClientScript.RegisterStartupScript(typeof(string), "", "<script> self.parent.closeTab(' 添加楼盘');</script>");//关闭选项卡

                        }
                        else if (typeid.Text == "2")
                        {
                            ClientScript.RegisterStartupScript(typeof(string), "", "<script> self.parent.closeTab(' 申请楼盘');</script>");//关闭选项卡
                        }

                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('保存失败,请输入正确的房号！')", true);
                    }
                }
                else
                {


                    int floor1 = _Convert.ToInt(txtFloor1.Text.ToString(), 0);//层数
                    int floor2 = _Convert.ToInt(txtFloor2.Text.ToString(), 0);





                    string otherNum1 = _Request.GetStringForm("otherNum1", ""); //房号别名中间
                    string otherNum2 = _Request.GetStringForm("otherNum2", "");

                    string number = "1,2,3,4,5,6,7,8,9";
                    string num3 = _Request.GetStringForm("txtNum1");
                    string num4 = _Request.GetStringForm("txtNum2");
                    if (isExists(num3) && isExists(num3))//如果房号中间是字母
                    {
                        //输出A-Z之间的字母
                        int rows = 0;
                        for (int j = floor1; j <= floor2; j++)
                        {
                            for (int i = Asc(num3); i <= Asc(num4); i++)
                            {
                                string name = Chr(i);//房号
                                if (otherNum1 != "")//房号别名
                                {
                                    if (isExists(otherNum1) && isExists(otherNum2))
                                    {
                                        int othercount = Asc(otherNum1);
                                        othername = Chr(othercount); //房号别名
                                        if (Asc(otherNum1) < Asc(otherNum2))
                                        {
                                            othercount++;
                                            otherNum1=Chr(othercount);
                                        }
                                    }
                                    else
                                    {
                                        if (number.Contains(otherNum1))
                                        {
                                            othername = "0" + otherNum1;
                                        }
                                        else
                                        {
                                            othername =  otherNum1;
                                        }
                                        if(_Convert.ToInt(otherNum1)<_Convert.ToInt(otherNum2))
                                              otherNum1 = Convert.ToString(_Convert.ToInt(otherNum1) + 1);
                                    }
                                }

                                if (!string.IsNullOrEmpty(strPer)) name = strPer + name;
                                if (!string.IsNullOrEmpty(strLast)) name = name + strLast;

                                string namepy1 = _Utility.GetChineseSpell(name);//房号拼音
                                string othernamepy1 = _Utility.GetChineseSpell(othername);
                                int count = ZLDC.Topo.BLL.Estate.RoomNoBLL.SelectRooms(bid.ToString(), j.ToString(), name);//判断房号是否存在
                                if (count == 0)
                                {
                                    rows = rbll.AddRoomNos(name, othername, j, bid, bname, mark, type, value, usage, this.info.m_sUserName, this.info.m_sDeptName, this.info.m_sDeptID, statusid, namepy1, othernamepy1, isvalid);
                                }

                            }
                            otherNum1=_Request.GetStringForm("otherNum1", ""); //房号别名中间
                            
                        }
                        if (rows > 0)
                        {
                            ClientScript.RegisterStartupScript(typeof(string), "", "<script>window.close();</script>");

                        }
                        else
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('申请房号失败，请输入正确的房号！')", true);

                        }
                    }
                    else
                    {
                        int num1 = _Request.GetIntForm("txtNum1", 0);        //房号中间
                        int num2 = _Request.GetIntForm("txtNum2", 0);
                        if (num2 >= num1)
                        {
                            int rows = 0;
                            for (int j = floor1; j <= floor2; j++)
                            {
                                floor = j;//楼层
                                for (int i = num1; i <= num2; i++)
                                {
                                    if (otherNum1 != "")
                                    {
                                        if (_Convert.ToInt(otherNum2, 0) >= _Convert.ToInt(otherNum1, 0))
                                        {
                                            if (number.Contains(otherNum1))
                                            {
                                                othername =  "0" + otherNum1;
                                            }
                                            else
                                            {
                                                othername =  otherNum1;
                                            }

                                        }
                                        else
                                        {
                                            othername = "";
                                        }
                                        otherNum1 = Convert.ToString(_Convert.ToInt(otherNum1) + 1);
                                    }
                                    string name = "";
                                    if (number.Contains(i.ToString()))
                                    {
                                        name = "0" + i.ToString();//房号
                                    }
                                    else
                                    {
                                        name =  i.ToString();//房号

                                    }

                                    if (!string.IsNullOrEmpty(strPer)) name = strPer + name;
                                    if (!string.IsNullOrEmpty(strLast)) name = name + strLast;

                                    string namepy1 = _Utility.GetChineseSpell(name);//房号拼音
                                    string othernamepy1 = _Utility.GetChineseSpell(othername);
                                    int count = ZLDC.Topo.BLL.Estate.RoomNoBLL.SelectRooms(bid.ToString(), floor.ToString(), name);//判断房号是否存在
                                    if (count == 0)
                                    {
                                        rows = rbll.AddRoomNos(name, othername, floor, bid, bname, mark, type, value, usage, this.info.m_sUserName, this.info.m_sDeptName, this.info.m_sDeptID, statusid, namepy1, othernamepy1, isvalid);
                                    }
                                }
                            }
                            if (rows > 0)
                            {
                                ClientScript.RegisterStartupScript(typeof(string), "", "<script>window.close();</script>");

                            }
                            else
                            {
                                Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('申请房号失败，请输入正确的房号！')", true);

                            }
                        }

                    }
                }
            }

            catch (Exception)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "alert('系统繁忙，请稍后再试！')", true);

            }
        }


        //字符转数字
        public static int Asc(string character)
        {
            if (character.Length == 1)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];
                return (intAsciiCode);
            }
            else
            {
                throw new Exception("Character is not valid.");
            }

        }

        //ASCII码转字符：

        public static string Chr(int asciiCode)
        {
            if (asciiCode >= 0 && asciiCode <= 255)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] byteArray = new byte[] { (byte)asciiCode };
                string strCharacter = asciiEncoding.GetString(byteArray);
                return (strCharacter);
            }
            else
            {
                throw new Exception("ASCII Code is not valid.");
            }
        }
        /// <summary>
        /// 判断字符是否是字母
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool isExists(string str)
        {
            return Regex.Matches(str, "[a-zA-Z]").Count > 0;
        }



    }
}
